﻿using DomainService.Service.Sys;
using Infrastructure;
using Infrastructure.Repository.Sys;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Model;
using Model.BusinessModel.MatchFormula;
using Model.BusinessModel.OutPut;
using Model.BusinessModel.OutPut.sys;
using Model.DomainModel.Sys;
using System.Data;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Utility;
using Utility.Enum;

namespace CoreDomain.BusinessCore
{
    /// <summary>
    /// 数据权限核心
    /// </summary>
    public static class DataAuthCore
    {
        #region 全局变量

        //数据权限仓储
        private static SysDataRuleRepository _sysDataRuleRepository = new SysDataRuleRepository();
        //用户仓储
        private static SysUserRepository _sysUserRepository = new SysUserRepository();
        //用户角色关系仓储
        private static SysUserRoleRelationRepository _sysUserRoleRelationRepository = new SysUserRoleRelationRepository();
        //匹配公式字符_英文，用于解析
        private static string matchingFormulaString = string.Empty;
        //匹配公式字符_中文，用于显示
        private static string matchingFormulaString_CN = string.Empty;
        //用户模型
        private static SysUser sysUserModel = new();
        //用户角色关系
        private static List<SysUserRoleRelationOutPut> sysUserRoleRelationOutPutList = new();

        #endregion

        #region 解析匹配公式

        /// <summary>
        /// 默认权限集合
        /// </summary>
        /// <returns></returns>
        public static List<SysDataRuleConfig> DefaultAuthList()
        {
            //默认数据源
            List<SysDataRuleConfig> sysDataRuleConfigs = new List<SysDataRuleConfig>() {
                new SysDataRuleConfig()
                {
                    ConditionalEquationValue=(int)ConditionalEquationValueEnum.包含+(int)ConditionalEquationValueEnum.不包含,
                    ShowControl = (int)ShowControlEnum.MultipleLayer,
                    ShowControlDataSource = (int)ShowControlDataSourceEnum.Personnel,
                    IsOpen = true,
                    PermissionsField = PermissionsFieldEnum.LoginUser.ToString(),
                    PermissionsFieldName = PermissionsFieldEnum.LoginUser.GetDescription(),
                },
                new SysDataRuleConfig()
                {
                    ConditionalEquationValue=(int)ConditionalEquationValueEnum.包含+(int)ConditionalEquationValueEnum.不包含,
                    ShowControl = (int)ShowControlEnum.MultipleLayer,
                    ShowControlDataSource = (int)ShowControlDataSourceEnum.Department,
                    IsOpen = true,
                    PermissionsField = PermissionsFieldEnum.LoginDepartment.ToString(),
                    PermissionsFieldName = PermissionsFieldEnum.LoginDepartment.GetDescription(),
                },
                new SysDataRuleConfig()
                {
                    ConditionalEquationValue=(int)ConditionalEquationValueEnum.包含+(int)ConditionalEquationValueEnum.不包含,
                    ShowControl = (int)ShowControlEnum.MultipleLayer,
                    ShowControlDataSource = (int)ShowControlDataSourceEnum.UserRole,
                    IsOpen = true,
                    PermissionsField = PermissionsFieldEnum.LoginRole.ToString(),
                    PermissionsFieldName = PermissionsFieldEnum.LoginRole.GetDescription(),
                }
            };
            return sysDataRuleConfigs;
        }

        /// <summary>
        /// 预览公式
        /// </summary>
        /// <param name="matchingDataInputs">公式数据</param>
        /// <param name="dataRuleConfigList">数据规则配置</param>
        /// <returns>返回解析好的字符串</returns>
        public static (string, string) PreviewFormula(List<MatchingDataInput> matchingDataInputs, List<SysDataRuleConfig> dataRuleConfigList)
        {
            matchingFormulaString = string.Empty;
            matchingFormulaString_CN = string.Empty;
            dataRuleConfigList.AddRange(DefaultAuthList());
            var data = GetMatchingFormulaString(matchingDataInputs, dataRuleConfigList);
            return data;
        }

        /// <summary>
        /// 递归匹配公式字符串
        /// </summary>
        /// <param name="matchingDataInputs">公式数据</param>
        /// <param name="dataRuleConfigList">数据规则配置</param>
        /// <returns>返回解析好的字符串</returns>
        private static (string, string) GetMatchingFormulaString(List<MatchingDataInput> matchingDataInputs, List<SysDataRuleConfig> dataRuleConfigList)
        {
            //循环公式数据
            foreach (var item in matchingDataInputs)
            {
                int count = 0;
                matchingFormulaString += "( ";
                matchingFormulaString_CN += "( ";

                //循环匹配条件
                foreach (var input in item.matchingWhere)
                {
                    count++;
                    var matchWhere = string.Empty;
                    var matchWhere_CN = string.Empty;
                    var permissionsFieldName = dataRuleConfigList.Where(f => f.PermissionsField == input.fieldKey).FirstOrDefault()?.PermissionsFieldName ?? string.Empty;
                    if (string.IsNullOrWhiteSpace(permissionsFieldName))
                        matchWhere_CN = input.fieldKey + string.Format(" {0} ", input.matchEquationKey);
                    else
                        matchWhere_CN = permissionsFieldName + string.Format(" {0} ", input.matchEquationKey);

                    matchWhere = input.fieldKey + string.Format(" {0} ", input.matchEquationKey);

                    //判断结果类型
                    if (input.showDataControl == (int)ShowControlEnum.Input)
                    {
                        matchWhere += string.Format("\"{0}\"", input.matchDataName);
                        matchWhere_CN += string.Format("\"{0}\"", input.matchDataName);
                    }
                    else if (input.showDataControl == (int)ShowControlEnum.Number)
                    {
                        matchWhere += string.Format("{0}", input.matchDataName);
                        matchWhere_CN += string.Format("{0}", input.matchDataName);
                    }
                    else
                    {
                        matchWhere += string.Format("\"{0}\"", input.matchDataName);
                        matchWhere_CN += string.Format("\"{0}\"", input.matchDataName);
                    }

                    if (item.matchGroup == "And")
                    {
                        if (count > 1)
                        {
                            matchingFormulaString = matchingFormulaString + " && " + matchWhere;
                            matchingFormulaString_CN = matchingFormulaString_CN + " 且 " + matchWhere_CN;
                        }
                        else
                        {
                            matchingFormulaString += matchWhere;
                            matchingFormulaString_CN += matchWhere_CN;
                        }
                    }
                    else
                    {
                        if (count > 1)
                        {
                            matchingFormulaString = matchingFormulaString + " || " + matchWhere;
                            matchingFormulaString_CN = matchingFormulaString_CN + " 或 " + matchWhere_CN;
                        }
                        else
                        {
                            matchingFormulaString += matchWhere;
                            matchingFormulaString_CN += matchWhere_CN;
                        }
                    }
                }

                //是否有子集，无子集根据层级添加括弧
                if (item.children.Count == 0)
                {
                    var kh = string.Empty;
                    for (int i = 0; i < item.level; ++i)
                    {
                        kh += " )";
                    }
                    matchingFormulaString += kh;
                    matchingFormulaString_CN += kh;
                }
                //是否有子集，有子集开始递归
                if (item.children.Count > 0)
                {
                    if (item.matchGroup == "And")
                    {
                        matchingFormulaString += " && ";
                        matchingFormulaString_CN += " 且 ";
                    }
                    else if (item.matchGroup == "Or")
                    {
                        matchingFormulaString += " || ";
                        matchingFormulaString_CN += " 或 ";
                    }
                    GetMatchingFormulaString(item.children, dataRuleConfigList);
                }
            }
            return (matchingFormulaString, matchingFormulaString_CN);

        }

        /// <summary>
        /// 通过数据字典，动态创建模型
        /// </summary>
        /// <param name="dictionary">字典数据</param>
        /// <returns></returns>
        public static object CreatModel(Dictionary<string, object> dictionary)
        {

            //创建动态代码。
            StringBuilder classSource = new StringBuilder();
            classSource.Append("public class DynamicModel \n");
            classSource.Append("{\n");
            //创建属性。
            foreach (var item in dictionary)
            {
                if (item.Value == null)
                    classSource.Append(" public string " + item.Key + " { get; set; }");
                else
                {
                    var type = item.Value.GetType().Name;
                    if (type == "Int64")
                        type = "long";
                    if (type == "Boolean")
                        type = "bool";
                    if (type == "JArray")
                        type = "object";
                    if (type == "String")
                        type = "string";
                    classSource.Append(" public " + type + " " + item.Key + " { get; set; }");
                }
            }
            classSource.Append("}");

            var syntaxTree = CSharpSyntaxTree.ParseText(classSource.ToString());
            var references = new List<MetadataReference>
                {
                    MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                };

            var compilation = CSharpCompilation.Create("DynamicModel.dll")
                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddReferences(references)
                .AddSyntaxTrees(syntaxTree);
            using var ms = new MemoryStream();
            var result = compilation.Emit(ms);
            if (!result.Success)
            {
                IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                    diagnostic.IsWarningAsError ||
                    diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("\t" + diagnostic.ToString());
                }
                return null;
            }

            ms.Seek(0, SeekOrigin.Begin);
            Assembly assembly = Assembly.Load(ms.ToArray());
            var dynamicModelType = assembly.GetType("DynamicModel");
            object instance = new();
            if (dynamicModelType != null)
            {
                // 使用动态创建的模型类
                instance = Activator.CreateInstance(dynamicModelType);
                // ...
            }
            foreach (var item in dictionary)
            {
                PropertyInfo _Property = instance.GetType().GetProperty(item.Key);
                if (_Property != null && _Property.CanRead)
                {
                    _Property.SetValue(instance, item.Value, null);
                }
            }
            return instance;
        }

        /// <summary>
        /// 是否拥有按钮权限
        /// </summary>
        /// <param name="dataRow">匹配数据</param>
        /// <param name="ruleStr">规则字符串</param>
        /// <returns></returns>
        public static Task<bool> IsHaveButtonAuth(LoginMatchModel model, string ruleStr)
        {
            //构建模型属性表达式树
            Type aType = model.GetType();
            var dataParameter = Expression.Parameter(aType);
            //执行表达式树
            var expar = DynamicExpressionParser.ParseLambda(new[] { dataParameter }, typeof(bool), ruleStr).Compile();
            var result = Convert.ToBoolean(expar.DynamicInvoke(model));
            return Task.FromResult(result);

        }

        #endregion

        #region 把公式转换成对应的sql


        /// <summary>
        /// 获取解析后的规则
        /// </summary>
        /// <param name="menuId">菜单key</param>
        /// <param name="ruleTypeEnum">规则类型</param>
        /// <returns></returns>
        public static List<MatchingDataInput> GetRuleJson(string menuId, RuleTypeEnum ruleTypeEnum)
        {
            var matchFormulaList = new List<MatchingDataInput>();
            var dataRule = _sysDataRuleRepository.GetMenuDataRuleList(menuId, (int)ruleTypeEnum).Where(f => f.IsOpen == true).FirstOrDefault()?.RuleJson ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(dataRule))
            {
                matchFormulaList = JsonSerializer.Deserialize<List<MatchingDataInput>>(dataRule);
            }
            if (matchFormulaList == null)
                matchFormulaList = new List<MatchingDataInput>();
            return matchFormulaList;
        }

        /// <summary>
        /// 获取解析后的规则
        /// </summary>
        /// <param name="menuId">菜单key</param>
        /// <param name="mainTableAlias">查询主表别名,没有别名就传主表名字</param>
        /// <param name="dataRuleType">规则类型</param>
        /// <returns></returns>
        public static string GetAnalysisRule(string menuId, string mainTableAlias, DataRuleConfigTypeEnum dataRuleType)
        {
            var dataRule = _sysDataRuleRepository.GetMenuDataRuleList(menuId, (int)dataRuleType).Where(f => f.IsOpen == true).FirstOrDefault()?.AnalysisRule ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(dataRule))
            {
                dataRule = dataRule.Replace(Const.MainTableAlias, mainTableAlias);
            }
            return dataRule;
        }

        /// <summary>
        /// 解析行数据权限规则，并转换成对应的sql
        /// </summary>
        /// <param name="mainTableAlias">查询主表别名,没有别名就传主表名字</param>
        /// <param name="menuId">菜单id</param>
        /// <param name="ruleData">规则数据</param>
        /// <param name="loginUserId">登陆人员id</param>
        /// <returns></returns>
        public static string GetRowDataAuthRoleSql(string mainTableAlias, string menuId, List<MatchingDataInput> ruleData, string loginUserId)
        {
            if (string.IsNullOrWhiteSpace(menuId))
                return string.Empty;
            if (string.IsNullOrWhiteSpace(mainTableAlias))
                ExceptionHelper.ThrowBusinessException("主表别名不能为空");
            if (string.IsNullOrWhiteSpace(loginUserId))
                ExceptionHelper.ThrowBusinessException("登录人员信息不能为空");

            if (ruleData.Count == 0)
                return string.Empty;

            //用户信息
            sysUserModel = _sysUserRepository.GetByKey(loginUserId, BaseSqlRepository.sysUser_selectByKeySql);
            if (sysUserModel == null)
                ExceptionHelper.ThrowBusinessException("当前登录人员不存在或已删除");
            if (sysUserModel.IsOpen == false)
                ExceptionHelper.ThrowBusinessException("当前登录人员未启用");

            //用户角色关系
            sysUserRoleRelationOutPutList = _sysUserRoleRelationRepository.GetSysUserRoleRelationsByUserId(loginUserId);

            mainTableAlias += ".";
            //解析规则sql
            string selectWhere = string.Empty;
            var dataRule = _sysDataRuleRepository.GetMenuDataRuleList(menuId, (int)DataRuleConfigTypeEnum.DataRowRuleConfig).Where(f => f.IsOpen == true).FirstOrDefault();

            //获取规则条件字符串
            var ruleSql = GetRuleString(ruleData, mainTableAlias.Trim());
            selectWhere = string.Format(" and {0}", ruleSql);

            return selectWhere;
        }

        /// <summary>
        /// 递归获取规则,并转换成sql
        /// </summary>
        /// <param name="matchingDataInput">规则数据</param>
        /// <param name="mainTableAlias">主表别名</param>
        /// <param name="isChildren">是否子集</param>
        /// <returns></returns>
        public static string GetRuleString(List<MatchingDataInput> matchingDataInput, string mainTableAlias)
        {
            StringBuilder stringBuilder = new StringBuilder();
            var i = 0;
            foreach (var entity in matchingDataInput)
            {
                //项条件
                if (entity.matchingWhere.Count > 0)
                {
                    foreach (var item in entity.matchingWhere)
                    {
                        //第一次进入不写符号
                        var matchGroup = string.Empty;
                        if (i == 0)
                            matchGroup = string.Empty;
                        else
                            matchGroup = entity.matchGroup;

                        bool isInEnum = Enum.IsDefined(typeof(PermissionsFieldEnum), item.fieldKey);
                        if (isInEnum)
                        {
                            //var sql = GetSplitExpression(item, matchGroup, mainTableAlias);
                            //stringBuilder.Append(sql);
                            var isTrue = isMatchingSuccess(item, sysUserModel, sysUserRoleRelationOutPutList);
                            if (!isTrue)
                            {
                                stringBuilder.Append(string.Format(" {0} 1!=1 ", matchGroup));
                            }
                            else
                            {
                                stringBuilder.Append(string.Format(" {0} 1=1 ", matchGroup));
                            }
                        }
                        else
                        {
                            stringBuilder.Append(string.Format(" {0} {1} {2} ",
                                  matchGroup, GetMatchingField(item.fieldKey, mainTableAlias), GetSplitSelectResultValue(item)));
                        }
                        i++;
                    }
                }

                //有子集
                if (entity.children.Count > 0)
                {
                    var sqlStr = GetRuleString(entity.children, mainTableAlias);
                    if (!string.IsNullOrEmpty(sqlStr))
                        stringBuilder.Append(string.Format(" {0} ({1}) ", entity.matchGroup, sqlStr));
                }
            }

            return stringBuilder.ToString();
        }


        /// <summary>
        /// 获取拼接表达式
        /// </summary>
        /// <param name="data">匹配条件</param>
        /// <param name="matchGroup">匹配组符号</param>
        /// <param name="mainTableAlias">主表别名</param>
        /// <returns></returns>
        private static string GetSplitExpression(matchingWhereData data, string matchGroup, string mainTableAlias)
        {
            var value = data.matchDataKey.ToString();

            string expression;
            if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.包含))
            {
                expression = string.Format(" \"{0}\".{1}({2}) ", value, data.matchEquationKey, data.fieldKey);
            }
            else if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
            {
                expression = string.Format(" \"{0}\".{1}({2})==false ", value, data.matchEquationKey, data.fieldKey);
            }
            else
            {
                expression = string.Format(" {0} == \"{1}\"", data.fieldKey, value);
            }


            return expression;
        }

        /// <summary>
        /// 获取拼接sql
        /// </summary>
        /// <param name="data">匹配条件</param>
        /// <param name="matchGroup">匹配组符号</param>
        /// <param name="mainTableAlias">主表别名</param>
        /// <returns></returns>
        private static string GetSplitSql(matchingWhereData data, string matchGroup, string mainTableAlias)
        {
            string sql = string.Empty;
            //当前登录人员匹配
            if (data.fieldKey == PermissionsFieldEnum.LoginUser.ToString())
            { }
            //当前登录角色匹配
            else if (data.fieldKey == PermissionsFieldEnum.LoginRole.ToString())
            {
                var splitWhereValue = GetSplitSelectResultValue(data);
                sql = string.Format(@" {0} EXISTS(select sr.RoleId from  Sys_Role as sr inner join   Sys_UserRoleRelation as rr on rr.RoleId = sr.RoleId  where {2}UserId = rr.UserId and sr.IsOpen = 1  and sr.RoleId {1}) ", matchGroup, splitWhereValue, mainTableAlias);
            }

            //当前登录部门匹配
            else if (data.fieldKey == PermissionsFieldEnum.LoginDepartment.ToString())
            { }
            else { }

            return sql;
        }


        /// <summary>
        /// 是否匹配成功
        /// </summary>
        /// <param name="data">条件数据</param>
        /// <returns></returns>
        private static bool isMatchingSuccess(matchingWhereData data, SysUser sysUser, List<SysUserRoleRelationOutPut> sysUserRoleRelationOutPuts)
        {
            bool isTrue = false;
            //当前登录人员匹配
            if (data.fieldKey == PermissionsFieldEnum.LoginUser.ToString())
            {
                var userIds = data.matchDataKey.ToString().Split(",").ToList();
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.包含))
                {
                    if (userIds.Contains(sysUser.UserId ?? string.Empty))
                        isTrue = true;
                }
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
                {
                    if (!userIds.Contains(sysUser.UserId ?? string.Empty))
                        isTrue = true;
                    else
                        isTrue = false;
                }
            }
            //当前登录角色匹配
            else if (data.fieldKey == PermissionsFieldEnum.LoginRole.ToString())
            {
                var roleIds = data.matchDataKey.ToString().Split(",").ToList();
                var loginRoleIds = sysUserRoleRelationOutPuts.Select(f => f.RoleId.ToString()).ToList();
                bool hasIntersection = roleIds.Intersect(loginRoleIds).Any();
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.包含))
                {
                    if (hasIntersection)
                        isTrue = true;
                }
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
                {
                    if (hasIntersection)
                        isTrue = false;
                    else
                        isTrue = true;
                }
            }
            //当前登录部门匹配
            else if (data.fieldKey == PermissionsFieldEnum.LoginDepartment.ToString())
            {
                var depIds = data.matchDataKey.ToString().Split(",").ToList();
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.包含))
                {
                    if (depIds.Contains(sysUser.DepartmentId ?? string.Empty))
                        isTrue = true;
                }
                if (data.matchEquationKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
                {
                    if (!depIds.Contains(sysUser.DepartmentId ?? string.Empty))
                        isTrue = true;
                    else
                        isTrue = false;
                }
            }
            else
                isTrue = false;
            return isTrue;
        }

        /// <summary>
        /// 获取匹配字段
        /// </summary>
        /// <param name="fieldKey">字段key</param>
        /// <param name="mainTableAlias">主表别名</param>
        /// <returns></returns>
        private static string GetMatchingField(string fieldKey, string mainTableAlias)
        {
            string fieldStr = fieldKey;
            if (!string.IsNullOrWhiteSpace(mainTableAlias) && fieldKey != ShowControlDataSourceEnum.UserRole.ToString())
                fieldStr = mainTableAlias + fieldStr;
            return fieldStr;
        }

        ///// <summary>
        ///// 获取匹配值
        ///// </summary>
        ///// <param name="matchingWhereData">匹配条件</param>
        ///// <returns></returns>
        //private static string GetMatchingValue(matchingWhereData matchingWhereData)
        //{
        //    string matchingValue = GetSplitSelectResultValue(matchingWhereData);
        //    return matchingValue;
        //}

        /// <summary>
        /// 获取拼接查询结果值
        /// </summary>
        /// <param name="matchingWhereData">匹配条件数据</param>
        /// <returns></returns>
        private static string GetSplitSelectResultValue(matchingWhereData matchingWhereData)
        {
            string splitValue = string.Empty;
            if (!string.IsNullOrEmpty(matchingWhereData.matchDataKey.ToString()))
            {
                if (matchingWhereData.matchEquationKey != EnumHelper.GetDescription(ConditionalEquationValueEnum.包含) && matchingWhereData.matchEquationKey != EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
                    splitValue = string.Format(" {0} '{1}' ", GetMatchingSymbolSql(matchingWhereData.matchEquationKey), matchingWhereData.matchDataKey);
                else
                    splitValue = string.Format(" {0} ({1}) ", GetMatchingSymbolSql(matchingWhereData.matchEquationKey), GetSelectValue(matchingWhereData.matchDataKey.ToString().Split(",").ToList()));
            }
            return splitValue;
        }

        /// <summary>
        /// 获取匹配符号
        /// </summary>
        /// <param name="matchSymbolKey">符号key</param>
        /// <returns></returns>
        private static string GetMatchingSymbolSql(string matchSymbolKey)
        {
            string matchSymbolStr = matchSymbolKey;
            if (matchSymbolKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.等于))
                matchSymbolStr = " = ";
            if (matchSymbolKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.包含))
                matchSymbolStr = " in ";
            if (matchSymbolKey == EnumHelper.GetDescription(ConditionalEquationValueEnum.不包含))
                matchSymbolStr = " not in ";
            return matchSymbolStr;
        }

        /// <summary>
        /// 获取查询值
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private static string GetSelectValue(List<string> list)
        {
            var value = string.Empty;
            foreach (var item in list)
            {
                value = value + ",'" + item + "'";
            }
            return value.Trim(',');
        }

        #endregion


        #region 数据列权限

        /// <summary>
        /// 递归获取规则,并转换成sql
        /// </summary>
        /// <param name="matchingDataInput">规则数据</param>
        /// <param name="mainTableAlias">主表别名</param>
        /// <param name="isChildren">是否子集</param>
        /// <returns></returns>
        public static bool GetDataColsAuth(List<MatchingDataInput> matchingDataInput, SysUser sysUser, List<SysUserRoleRelationOutPut> sysUserRoleRelationOutPuts)
        {
            bool isTrue = false;
            foreach (var entity in matchingDataInput)
            {
                //项条件
                if (entity.matchingWhere.Count > 0)
                {
                    foreach (var item in entity.matchingWhere)
                    {


                        bool isInEnum = Enum.IsDefined(typeof(PermissionsFieldEnum), item.fieldKey);
                        if (isInEnum)
                        {
                            isTrue = isMatchingSuccess(item, sysUser, sysUserRoleRelationOutPuts);
                            if (isTrue == false && entity.matchGroup == "And")
                                return isTrue;
                            if (isTrue == true && entity.matchGroup == "Or")
                                return isTrue;
                        }
                        else
                        {

                        }
                    }
                }

                //有子集
                if (entity.children.Count > 0)
                {
                    isTrue = GetDataColsAuth(entity.children, sysUser, sysUserRoleRelationOutPuts);
                }
            }

            return isTrue;

        }
        #endregion

    }
}
